<?php

namespace app\zhonghang\controller;

use think\Controller;
use youwen\exwechat\api\accessToken;
use youwen\exwechat\api\OAuth\OAuth;
use think\Config;
use think\Db;
define('CURL_LOG', true);

class Demoauth extends Controller
{
    public $appid = '';
    public $appsec = '';
    public static $tjid = '';

    public function __construct()
    {
        parent::__construct();

        $this->appid = Config::get('appid');
        $this->appsec = Config::get('appsec');
    }

    public function index11111()
    {
        return $this->fetch();
    }

    public function snsapi_base()
    {

        $redirect_uri = url('callback_base', '', false, true);
        $scope = 'snsapi_base';
        $state = '123';
        $redirect_uri = urlencode($redirect_uri);
        $OAuth = new OAuth($this->appid, $this->appsec);
        $url = $OAuth->getCodeUrl($redirect_uri, $scope, $state);
        echo '<pre>';
        print_r($url);
        exit('</pre>');
        header('Location: ' . $url);
        exit();
        // $this->assign('url', $url);
        // $this->assign('redirect_uri', $redirect_uri);
        // return $this->fetch();
    }

    ///微信入口
    public function index()
    {
        //如果通过扫码推荐进入type=1则获得推荐人id   否则正常进入外卖点餐
         if(!empty($_GET['idd'])){
			 cookie('tjid',$_GET['idd']);

         }
		if($_GET['type']==1){
			$redirect_uri = url('callback_userinfo', '', false, true);
            $scope = 'snsapi_userinfo';
            $state = '';
            $redirect_uri = urlencode($redirect_uri);
            $OAuth = new OAuth($this->appid, $this->appsec);
            $url = $OAuth->getCodeUrl($redirect_uri, $scope, $state);
            header('Location: ' . $url);
            exit();
		}else{
			if (cookie('user') == '') {
            $redirect_uri = url('callback_userinfo', '', false, true);
            $scope = 'snsapi_userinfo';
            $state = '';
            $redirect_uri = urlencode($redirect_uri);
            $OAuth = new OAuth($this->appid, $this->appsec);
            $url = $OAuth->getCodeUrl($redirect_uri, $scope, $state);
            header('Location: ' . $url);
            exit();
        } else {
            $token = $this->gettoken(cookie('user')['member_id']);
            $this->headurl($token);
        }
		}


    }

    //成功跳转地址
    public function headurl($token)
    {
        $url = "http://wm.quyum.cn/dist/index.html#/?token=".$token;
        header('Location: ' . $url);
        exit();
    }

    ///失败跳转地址
    public function headerror($message)
    {

    }

    ////不需要授权页面
    public function callback_base()
    {
        define(CURL_LOG, true);
        $OAuth = new OAuth($this->appid, $this->appsec);
        $ret = $OAuth->getToken($_GET['code']);
        if (isset($ret['errcode'])) {
            echo '<pre>';
            print_r($ret);
            exit('</pre>');
        }
        $this->_saveAccess($ret);
        echo '<pre>';
        print_r($_GET);
        echo '<br/>';
        print_r($ret);
        exit('</pre>');
    }

    /*用户信息回调*/
    public function callback_userinfo()
    {
        define(CURL_LOG, true);
        $OAuth = new OAuth($this->appid, $this->appsec);
        $ret = $OAuth->getToken($_GET['code']);

        if (isset($ret['errcode'])) {
            $this->headerror($ret);
        }
        $info = $OAuth->getUserInfo($ret['access_token'], $ret['openid']);
        if (isset($info['errcode'])) {
            $this->headerror($info);
        }
        $check = $OAuth->checkToken($ret['access_token'], $ret['openid']);
        // $refresh = $OAuth->refreshToken($ret['refresh_token']);
        $id = $this->_saveAccess($ret, config('tablename'));
        $result = $this->_saveUserInfo($info, config('tablename'), $id);
        $token = $this->gettoken($result['member_id']);
        if ($result) {
            cookie('user', $result);
            $this->headurl($token);
        } else {
            $this->headerror();
        }
    }

    /**
     * 存在更新，不存在则插入
     * @DateTime 2017-03-25T12:33:06+0800
     *
     * 这个地方建一个联合索引应该可以用replace
     */
    private function _saveAccess($data, $tablename)
    {

        $check = db($tablename)->where(['openid' => $data['openid']])->find();

        if ($check) {

			$result = db($tablename)->where(['openid' => $data['openid'],'recommend_id'=>0])->find();

			if($result){
				$data['recommend_id'] = cookie('tjid')?cookie('tjid'):0;
				$data['recommend_time'] = cookie('tjid')?time():0;
			}
            $ret = db($tablename)->where(['openid' => $data['openid']])->strict(false)->update($data);
            return $check['member_id'];
        } else {
            $data['createTime'] = time();
            $data['recommend_id'] = cookie('tjid')?cookie('tjid'):0;
            $data['recommend_time'] = cookie('tjid')?time():0;

            $ret = db($tablename)->strict(false)->insertGetId($data);
            return $ret;
        }
    }

    /**
     *$id新添加的id
     * 修改全部信息
     */

    private function _saveUserInfo($userinfo, $tablename, $id)
    {
        $sql = 'UPDATE wm_' . $tablename . ' SET ';
        $str = '';
        unset($userinfo['language']);
        unset($userinfo['privilege']);
        //dump($userinfo);die;
        foreach ($userinfo as $key => $value) {
            if (is_array($value)) {
                $value = json_encode($value);
            }
            $str .= " `$key`='$value',";
        }
        $str = rtrim($str, ',') . 'WHERE `member_id`=' . $id;
        $ret = db($tablename)->execute($sql . $str);
        if ($ret === false) {
            return false;
        }

        return db($tablename)->where('member_id', $id)->find();
    }

    /*
     * 用户token生成方法
     * */
    function gettoken($namespace = null)
    {
        $uid = uniqid("", true);

        $data = $namespace;
        $data .= $_SERVER ['REQUEST_TIME'];     // 请求那一刻的时间戳  
        $data .= $_SERVER ['HTTP_USER_AGENT'];  // 获取访问者在用什么操作系统  
        $data .= $_SERVER ['SERVER_ADDR'];      // 服务器IP  
        $data .= $_SERVER ['SERVER_PORT'];      // 端口号  
        $data .= $_SERVER ['REMOTE_ADDR'];      // 远程IP  
        $data .= $_SERVER ['REMOTE_PORT'];      // 端口信息  

        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        //$guid = '{' . substr ( $hash, 0, 8 ) . '-' . substr ( $hash, 8, 4 ) . '-' . substr ( $hash, 12, 4 ) . '-' . substr ( $hash, 16, 4 ) . '-' . substr ( $hash, 20, 12 ) . '}';
        $result = DB::name("member_token")->where('uid',$namespace)->delete();
        $data=array();
        $data['uid'] = $namespace;
        $data['token'] = $hash;
        $result = DB::name("member_token")->insert($data);
        return $result?$hash:'';
    }
}